<?php
/*
Plugin Name: SAE Features Support
Description: Let WordPress run in Sina App Engine better.
Version: 0.0.1
Plugin URI: http://sae.phphy.com/
Author: tmwin
Install this file to wp-content/mu-plugins/sae-support.php
*/

if (strpos($_SERVER['HTTP_USER_AGENT'], 'qiniu-imgstg-spider') !== false) {
    header('HTTP/1.1 503 Service Temporarily Unavailable');
    exit();
}

// 移除左上角图标
function admin_bar_remove()
{
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('wp-logo');
}
add_action('wp_before_admin_bar_render', 'admin_bar_remove', 0);

// Gravatar头像替换
function get_cn_avatar($avatar)
{
    $avatar = str_replace(array("www.gravatar.com","0.gravatar.com","1.gravatar.com","2.gravatar.com"), "cn.gravatar.com", $avatar);
    return $avatar;
}
add_filter("get_avatar", "get_cn_avatar");

// 静态资源替换
if (is_blog_installed()) {
    add_action("wp_loaded", 'static_start_ob_cache');
}

function static_start_ob_cache()
{
    is_admin()?ob_start('admin_static_replace'):ob_start('static_replace');
}

function admin_static_replace($html)
{
    $html = str_replace('ajax.googleapis.com', 'ajax.useso.com', str_replace('fonts.googleapis.com', 'fonts.useso.com', $html));
    return $html;
}

function static_replace($html)
{
    $cdn_exts = 'js|css|png|jpg|jpeg|gif|ico';
    $cdn_dirs = str_replace('-', '\-', 'wp-content|wp-includes');
    $regex = '/' . str_replace('/', '\/', home_url()) . '\/((' . $cdn_dirs . ')\/[^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_exts . '))([\"\\\'\s\?]{1})/';
    $html = preg_replace($regex, 'http://' . QN_DOMAIN . '/$1$4', $html);
    $html = str_replace('ajax.googleapis.com', 'ajax.useso.com', str_replace('fonts.googleapis.com', 'fonts.useso.com', $html));
    return $html;
}
    
// 禁用emoji
function disable_emojis_tinymce($plugins)
{
    if (is_array($plugins)) {
        return array_diff($plugins, array('wpemoji'));
    } else {
        return array();
    }
}

function disable_emoji()
{
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('admin_print_scripts', 'print_emoji_detection_script');
    remove_action('wp_print_styles', 'print_emoji_styles');
    remove_action('admin_print_styles', 'print_emoji_styles');
    remove_filter('the_content_feed', 'wp_staticize_emoji');
    remove_filter('comment_text_rss', 'wp_staticize_emoji');
    remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
    add_filter('tiny_mce_plugins', 'disable_emojis_tinymce');
}
add_action('init', 'disable_emoji');

/** 七牛文件上传 **/
// token
function storage_uploadtoken()
{
    include_once ('inc/class-qiniu.php');
    $qiniu = new QiniuStorage();
    $param['saveKey'] = 'uploads/$(year)/$(mon)/$(fname)';
    
    return $qiniu->UploadToken($param);
}
// 上传目录
function upload_dir($uploads)
{
    $uploads['basedir'] = SAE_TMP_PATH . 'uploads';
    $uploads['path'] = SAE_TMP_PATH . 'uploads' . $uploads['subdir'];
    $uploads['baseurl'] = 'http://' . QN_DOMAIN . '/uploads';
    $uploads['url'] = 'http://' . QN_DOMAIN . '/uploads' . $uploads['subdir'];
    
    return $uploads;
}
// 上传文件名
function upload_filename($filename)
{
    $filename = substr(md5(sha1(uniqid(mt_rand(), 1))), 8, 16) . '.' . pathinfo($filename, PATHINFO_EXTENSION);
    
    return $filename;
}
// 上传处理
function handle_upload($file){
    $tmp = @file_get_contents($file['file']);
    include_once ('inc/class-qiniu.php');
    $qiniu = new QiniuStorage();
    $upfile = array(
        'name' => 'file',
        'fileName' => str_replace('http://' . QN_DOMAIN . '/', '', $file['url']),
        'fileBody' => $tmp
    );
    $param['saveKey'] = 'uploads/$(year)/$(mon)/$(fname)';
    $qiniu->upload($param, $upfile);
    
    return $file;
}
// 背景裁剪上传
function upload_all($file = null, $aid = null){
    upload_directory(SAE_TMP_PATH . 'uploads');

    return $file;
}

function upload_directory($directory){
    if(substr($directory, -1, 1) === '/')
        $directory = substr($directory, 0, strlen($directory)-1);
    $handle = opendir($directory);
    if($handle){
        while(false !== ($file = readdir($handle))){
            if($file !== '.' && $file !== '..'){
                if(is_dir($directory.'/'.$file)){
                    upload_directory($directory.'/'.$file);
                }else{
                    upload_file($directory.'/'.$file);
                }
            }
        }
    }
}

function upload_file($file, $clean = true)
{
    $tmp = @file_get_contents($file);
    include_once ('inc/class-qiniu.php');
    $qiniu = new QiniuStorage();
    $upfile = array(
        'name' => 'file',
        'fileName' => str_replace(SAE_TMP_PATH, '', $file),
        'fileBody' => $tmp
    );
    $param['saveKey'] = 'uploads/$(year)/$(mon)/$(fname)';
    $qiniu->upload($param, $upfile);
}
// 保存网络图片
function upload_remote($content){
    return preg_replace_callback('|<img.*?src=\\\\"(.*?)\\\\".*?>|i','static_replace_remote_image',$content);
}

function static_replace_remote_image($matches)
{
    $image_url = $matches[1];
    if (empty($image_url))
        return;
    if (strpos($image_url, Q_Domain) === false) {
        $ext = pathinfo($image_url, PATHINFO_EXTENSION);
        if ($ext)
            $ext = '.' . $ext;
        $key = 'uploads/' . date('Y') . '/' . date('m') . '/' . substr(md5(sha1(uniqid(mt_rand(), 1))), 8, 16) . $ext;
        $tmp = @file_get_contents($image_url);
        include_once ('inc/class-qiniu.php');
        $qiniu = new QiniuStorage();
        $upfile = array(
            'name' => 'file',
            'fileName' => $key,
            'fileBody' => $tmp
        );
        $param['saveKey'] = 'uploads/$(year)/$(mon)/$(fname)';
        $result = $qiniu->upload($param, $upfile);
        if ($result) {
            $matches[0] = str_replace($image_url, 'http://' . QN_DOMAIN . '/' . $key, $matches[0]);
        }

        return $matches[0];
    }

    return $matches[0];
}
// 缩略图属性
function upload_thumb($metadata)
{
    $file = basename($metadata['file']);
    if (isset($metadata['sizes'])) {
        foreach ($metadata['sizes'] as $size_name => $image_meta) {
            $metadata['sizes'][$size_name]['file'] = $file . '?imageView2/0/w/' . $image_meta['width'] . '/h/' . $image_meta['height'];
        }
    }
    return $metadata;
}
// 保存编辑图片
function save_image($saved, $filename, $image, $mime_type, $post_id)
{
    ob_start();
    $image->stream($mime_type);
    $tmp = ob_get_contents();
    ob_end_clean ();
    include_once ('inc/class-qiniu.php');
    $qiniu = new QiniuStorage();
    $upfile = array(
        'name' => 'file',
        'fileName' => str_replace(SAE_TMP_PATH, '', $filename),
        'fileBody' => $tmp
    );
    $param['saveKey'] = 'uploads/$(year)/$(mon)/$(fname)';
    $qiniu->upload($param, $upfile);
    
    return true;
}
// 保存缩略图属性
function save_thumb($metadata)
{
    ob_end_clean();
    $file = basename($metadata['file']);
    if (isset($metadata['sizes'])) {
        foreach ($metadata['sizes'] as $size_name => $image_meta) {
            $metadata['sizes'][$size_name]['file'] = $file . '?imageView2/0/w/' . $image_meta['width'] . '/h/' . $image_meta['height'];
        }
    }
    return $metadata;
}
// 删除文件
function delete_file($file){
    $file = preg_replace('/\?(.*?)$/', '', str_replace(SAE_TMP_PATH, '', $file));
    include_once ('inc/class-qiniu.php');
    $qiniu = new QiniuStorage();
    $qiniu->del($file);
    
    return $file;
}

add_filter('upload_dir', 'upload_dir');
add_filter('sanitize_file_name', 'upload_filename');
add_filter('wp_handle_upload', 'handle_upload');
add_filter('wp_create_file_in_uploads', 'upload_all');
add_filter('content_save_pre', 'upload_remote');
add_filter('wp_generate_attachment_metadata', 'upload_thumb', 999);
add_filter('wp_save_image_editor_file', 'save_image', 10, 5);
add_filter('wp_update_attachment_metadata', 'save_thumb');
add_filter('wp_delete_file', 'delete_file');

// SMTP邮件设置
function phpmailer_init_smtp($phpmailer)
{
    $phpmailer->Mailer = WPMS_MAILER;
    if (WPMS_SET_RETURN_PATH)
        $phpmailer->Sender = $phpmailer->From;
    if (WPMS_MAILER == 'smtp') {
        $phpmailer->SMTPSecure = WPMS_SSL;
        $phpmailer->Host = WPMS_SMTP_HOST;
        $phpmailer->Port = WPMS_SMTP_PORT;
        if (WPMS_SMTP_AUTH) {
            $phpmailer->SMTPAuth = true;
            $phpmailer->Username = WPMS_SMTP_USER;
            $phpmailer->Password = WPMS_SMTP_PASS;
        }
    }
    $phpmailer = apply_filters('wp_mail_smtp_custom_options', $phpmailer);
}

add_action('phpmailer_init', 'phpmailer_init_smtp');

// 网站地图
function escape_xml($string)
{
    return str_replace(array('&','"',"'",'<','>'), array('&amp;','&quot;','&apos;','&lt;','&gt;'), $string);
}

function build_sitemap_xml($xml_contents){
    $blog_url = home_url();
    $blogtime = current_time('timestamp', '1');
    $blog_time = date("Y-m-d\TH:i:s+00:00",$blogtime);

    $xml_begin = '<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="' . $blog_url .'/wp-content/mu-plugins/inc/sitemap.xsl"?><urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    $xml_home = "<url><loc>$blog_url</loc><lastmod>$blog_time</lastmod><changefreq>daily</changefreq><priority>1.0</priority></url>";
    $xml_end = '</urlset>';
    if($xml_contents){
        $xml = $xml_begin.$xml_home.$xml_contents.$xml_end;

        $kv = new SaeKV();
        $kv->init();
        $kv->set("sitemap.xml", $xml);
    }
}

function build_sitemap($mes = 0)
{
    global $wpdb, $posts;

    $sql_mini = "select ID,post_modified,post_date,post_type FROM $wpdb->posts
    WHERE post_password = ''
    AND (post_type='post' or post_type='page')
    AND post_status = 'publish'
    ORDER BY post_modified DESC
    LIMIT 0,1000
    ";
    $recentposts_mini = $wpdb->get_results($sql_mini);
    if ($recentposts_mini) {
        foreach ($recentposts_mini as $post) {
            if ($post->post_type == 'page') {
                $loc = get_page_link($post->ID);
                $loc = escape_xml($loc);
                if (! $loc) {
                    continue;
                }
                if ($post->post_modified == '0000-00-00 00:00:00') {
                    $post_date = $post->post_date;
                } else {
                    $post_date = $post->post_modified;
                }
                $lastmod = date("Y-m-d\TH:i:s+00:00", strtotime($post_date));
                $changefreq = 'weekly';
                $priority = '0.3';
                $xml_contents_page .= "<url>";
                $xml_contents_page .= "<loc>$loc</loc>";
                $xml_contents_page .= "<lastmod>$lastmod</lastmod>";
                $xml_contents_page .= "<changefreq>$changefreq</changefreq>";
                $xml_contents_page .= "<priority>$priority</priority>";
                $xml_contents_page .= "</url>";
            } else {
                $loc = get_permalink($post->ID);
                $loc = escape_xml($loc);
                if (! $loc) {
                    continue;
                }
                if ($post->post_modified == '0000-00-00 00:00:00') {
                    $post_date = $post->post_date;
                } else {
                    $post_date = $post->post_modified;
                }
                $lastmod = date("Y-m-d\TH:i:s+00:00", strtotime($post_date));
                $changefreq = 'monthly';
                $priority = '0.6';
                $xml_contents_post .= "<url>";
                $xml_contents_post .= "<loc>$loc</loc>";
                $xml_contents_post .= "<lastmod>$lastmod</lastmod>";
                $xml_contents_post .= "<changefreq>$changefreq</changefreq>";
                $xml_contents_post .= "<priority>$priority</priority>";
                $xml_contents_post .= "</url>";
            }
        }
        $category_ids = get_all_category_ids();
        if ($category_ids) {
            foreach ($category_ids as $cat_id) {
                $loc = get_category_link($cat_id);
                $loc = escape_xml($loc);
                if (! $loc) {
                    continue;
                }
                $lastmod = date("Y-m-d\TH:i:s+00:00", current_time('timestamp', '1'));
                $changefreq = 'Weekly';
                $priority = '0.3';
                $xml_contents_cat .= "<url>";
                $xml_contents_cat .= "<loc>$loc</loc>";
                $xml_contents_cat .= "<lastmod>$lastmod</lastmod>";
                $xml_contents_cat .= "<changefreq>$changefreq</changefreq>";
                $xml_contents_cat .= "<priority>$priority</priority>";
                $xml_contents_cat .= "</url>";
            }
        }

        $all_the_tags = get_tags();
        if ($all_the_tags) {
            foreach ($all_the_tags as $this_tag) {
                $tag_id = $this_tag->term_id;
                $loc = get_tag_link($tag_id);
                $loc = escape_xml($loc);
                if (! $loc) {
                    continue;
                }
                $lastmod = date("Y-m-d\TH:i:s+00:00", current_time('timestamp', '1'));
                $changefreq = 'Weekly';
                $priority = '0.3';
                $xml_contents_tag .= "<url>";
                $xml_contents_tag .= "<loc>$loc</loc>";
                $xml_contents_tag .= "<lastmod>$lastmod</lastmod>";
                $xml_contents_tag .= "<changefreq>$changefreq</changefreq>";
                $xml_contents_tag .= "<priority>$priority</priority>";
                $xml_contents_tag .= "</url>";
            }
        }

        $xml_contents = $xml_contents_post . $xml_contents_page . $xml_contents_cat . $xml_contents_tag;
    }

    build_sitemap_xml($xml_contents, $mes);
}

function sitemap_by_post($post_ID)
{
    build_sitemap();
    return $post_ID;
}

function sitemap_auto_daily() {
    $kv = new SaeKV();
    $kv->init();
    $data = $kv->get("sitemap.xml");
    if(!$data){
        build_sitemap();
    }

    $updatePeri = 60*60*24;
    wp_schedule_single_event(time()+$updatePeri, 'do_this_auto_daily');
    add_action('do_this_auto_daily','build_sitemap',2,0);
}

function custom_template_redirect() {
    global $wp_query;

    $reditect_page = $wp_query->query['name'];
    if ($reditect_page) {
        switch ($reditect_page) {
            case 'sitemap.xml':
                header('HTTP/1.1 200 OK');
                header("Content-type: text/xml");
                $kv = new SaeKV();
                $kv->init();
                $data = $kv->get("sitemap.xml");
                die($data);
                break;
        }
    }
}

add_action('publish_post', 'sitemap_by_post');
add_action('save_post', 'sitemap_by_post');
add_action('edit_post', 'sitemap_by_post');
add_action('delete_post', 'sitemap_by_post');
add_action("template_redirect", 'custom_template_redirect');
if (is_blog_installed()) {
    add_action('init', 'sitemap_auto_daily', 1001, 0);
}

// 自动生成别名
function using_hashid_as_slug($post_id, $post)
{
    global $post_type;
    if ($post_type == 'post') {
        if (wp_is_post_revision($post_id))
            return false;
        remove_action('save_post', 'using_hashid_as_slug');
        wp_update_post(array('ID' => $post_id,'post_name' => shortUrl($post_id)));
        add_action('save_post', 'using_hashid_as_slug');
    }
}

function shortUrl($long_url)
{
    $key = AUTH_KEY;
    $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $hex = hash('md5', $long_url . $key);
    $hexLen = strlen($hex);
    $subHexLen = $hexLen / 8;
    $output = array();
    for ($i = 0; $i < $subHexLen; $i ++) {
        $subHex = substr($hex, $i * 8, 8);
        $idx = 0x3FFFFFFF & (1 * ('0x' . $subHex));
        $out = '';
        for ($j = 0; $j < 6; $j ++) {
            $val = 0x0000003D & $idx;
            $out .= $base32[$val];
            $idx = $idx >> 5;
        }
        $output[$i] = $out;
    }
    return $output[0];
}
add_action('save_post', 'using_hashid_as_slug', 10, 2);

?>